package com.goldplusgold.tradedelay.app.trade.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.ErrorCodeConstant;
import com.goldplusgold.tradedelay.app.home.serivce.HomeService;
import com.goldplusgold.tradedelay.app.home.pojo.TDLogin;
import com.goldplusgold.tradedelay.app.trade.networkservice.ApiConfig;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.Switch;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.support.lib.utils.NetWorkConstant;

import butterknife.BindView;


public class ContractTradeFragment extends BaseFragment implements Handler.Callback {

    @BindView(R.id.trade_layout)
    RelativeLayout tradeLayout;
    private Handler handler = new Handler(this);
    private String mCurrentUrl = null;

    public static ContractTradeFragment newInstance() {
        ContractTradeFragment fragment = new ContractTradeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_contrac_trade;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            new QuerySwitchStateTask().execute(AsyncTask.TYPE_NET);
        }
    }

    @Override
    protected void initView() {
        super.initView();
    }


    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE:
                String message = (String) msg.obj;
                ActivityUtils.forceQuit(getActivity(), message);
                break;
        }

        return true;
    }

    public class QuerySwitchStateTask extends AsyncTask<Void, Void, Switch> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Switch doInBackground(Void... params) {
            Switch switchValue = null;
            try {
                switchValue = TradeService.getInstance().getSwitch();
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return switchValue;
        }

        @Override
        protected void onPostExecute(Switch switchValue) {
            super.onPostExecute(switchValue);
            if (switchValue == null || getFragmentManager() == null) {
                return;
            }
            if (!switchValue.isSwitchFlag()) {
                if (!com.goldplusgold.tradedelay.app.home.serivce.ApiConfig._TREE_DOWNLOAD_URL.equals(mCurrentUrl))
                    getFragmentManager().beginTransaction().replace(R.id.trade_layout, TradeWebViewFragment.newInstance(com.goldplusgold.tradedelay.app.home.serivce.ApiConfig._TREE_DOWNLOAD_URL, 1)).commitAllowingStateLoss();
                mCurrentUrl = com.goldplusgold.tradedelay.app.home.serivce.ApiConfig._TREE_DOWNLOAD_URL;
            } else {
                mCurrentUrl = null;
                new QueryTdLoginStateTask().execute(AsyncTask.TYPE_NET);
            }
        }
    }


    public class QueryTdLoginStateTask extends AsyncTask<Void, Void, TDLogin> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected TDLogin doInBackground(Void... params) {

            try {
                TDLogin tdLoginState = HomeService.getInstance().getTDLoginState();
                if (tdLoginState != null) {
                    return tdLoginState;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(TDLogin tdLogin) {
            super.onPostExecute(tdLogin);
            if (tdLogin == null || getFragmentManager() == null) {
                return;
            }
            if (tdLogin.getStatus()) {
                getFragmentManager().beginTransaction().replace(R.id.trade_layout, TradeFragment.newInstance()).commitAllowingStateLoss();
            } else {
                getFragmentManager().beginTransaction().replace(R.id.trade_layout, TradeWebViewFragment.newInstance(ApiConfig.TRADE_LOGIN, 1)).commitAllowingStateLoss();
            }
        }
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }


}
